package com.bckj.freshnow.order.trade.extension;

import com.alibaba.cola.extension.Extension;
import com.bckj.fastboot.core.execution.ExecutionChain;
import com.bckj.freshnow.common.constant.TradeOrderConstants;
import com.bckj.freshnow.order.model.CreateTradeOrderRequest;
import com.bckj.freshnow.order.model.CreateTradeOrderResponse;
import com.bckj.freshnow.order.trade.execution.MarketingLockExecution;
import com.bckj.freshnow.order.trade.execution.StockDecreaseExecution;
import com.bckj.freshnow.order.trade.execution.create.*;
import com.bckj.freshnow.order.trade.fsm.TradeOrderContext;
import jakarta.annotation.PostConstruct;

@Extension(bizId = TradeOrderConstants.BIZ_ID_CUSTOM)
public class CustomCreateTradeOrderExtPt implements CreateTradeOrderExtPt {

    private ExecutionChain preCreateTradeOrderChain;
    private ExecutionChain pricingTradeOrderChain;
    private ExecutionChain createTradeOrderChain;

    @PostConstruct
    public void init() {
        preCreateTradeOrderChain = ExecutionChain.newChain()
                .add(CreateTradeOrderCheckRequestExecution.class)
                .add(CreateTradeOrderInitExecution.class)
                .add(CreateTradeOrderGoodsInitExecution.class)
                .add(CreateTradeOrderSplitExecution.class)
                .add(CreateTradeOrderTempExecution.class);

        pricingTradeOrderChain = ExecutionChain.newChain()
                .add(CreateTradeOrderTempExecution.class);

        createTradeOrderChain = ExecutionChain.newChain()
                .add(CreateTradeOrderTempExecution.class)
                .add(CreateTradeOrderCheckExecution.class)
                .add(StockDecreaseExecution.class)
                .add(MarketingLockExecution.class)
                .add(CreateTradeOrderSaveExecution.class)
                .add(CreateTradeOrderBillExecution.class);
    }

    @Override
    public CreateTradeOrderResponse preCreate(CreateTradeOrderRequest request) {
        var ctx = new TradeOrderContext();
        ctx.setRequest(request);
        preCreateTradeOrderChain.execute(ctx);
        CreateTradeOrderResponse response = new CreateTradeOrderResponse();
        response.setParentOrderNo(ctx.getParentOrderNo());
        response.setParentOrder(ctx.getParentOrder());
        return response;
    }

    @Override
    public CreateTradeOrderResponse pricing(CreateTradeOrderRequest request) {
        var ctx = new TradeOrderContext();
        ctx.setRequest(request);
        pricingTradeOrderChain.execute(ctx);
        return (CreateTradeOrderResponse) ctx.getResponse();
    }

    @Override
    public CreateTradeOrderResponse create(CreateTradeOrderRequest request) {
        var ctx = new TradeOrderContext();
        ctx.setRequest(request);
        createTradeOrderChain.execute(ctx);
        return (CreateTradeOrderResponse) ctx.getResponse();
    }
}
